//
//  LoginViewController.swift
//  甜言蜜语
//
//  Created by 王剑伟 on 16/7/4.
//  Copyright © 2016年 wl. All rights reserved.
//

import UIKit
import SVProgressHUD
class LoginViewController: UIViewController, UITextFieldDelegate{
    
    @IBOutlet weak var user: UITextField!
    @IBOutlet weak var password: UITextField!
    
    var json: String?
    var type: String?
    var number: String?
    var modelList: loginInfo?{
        didSet{
            
        }
    }
    var msg: regiestInfo?
    override func viewDidLoad() {
        super.viewDidLoad()
        self.user.delegate = self
        self.password.delegate = self
        
        self.password.secureTextEntry = true
        publicMethod.setHUDStyle()
        
    
        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
     override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.barTintColor = NAVIGATIONBAR_RED_COLOR
        self.tabBarController?.tabBar.hidden = true
    }
    override func viewWillDisappear(animated: Bool) {
        SVProgressHUD.dismiss()
        super.viewWillDisappear(animated)
    }
    
   //MARK:UITextFieldDelegate
    func textFieldShouldBeginEditing(textField: UITextField) -> Bool{
        if textField == self.user{
            self.user.layer.borderWidth = 1.0
            self.user.layer.borderColor = NAVIGATIONBAR_RED_COLOR.CGColor
        }else if textField == self.password{
            self.password.layer.borderWidth = 1.0
            self.password.layer.borderColor = NAVIGATIONBAR_RED_COLOR.CGColor
        }
        return true
    }
    @IBAction func loginBntClicked(sender: UIButton){
        if self.user.text == ""{
            SVProgressHUD.showErrorWithStatus("请输入用户名")
           
            return
        }
        if self.password.text == ""{
             SVProgressHUD.showErrorWithStatus("请输入密码")
           
            return
        }else{
            let token = NSUserDefaults.standardUserDefaults().stringForKey("k_UD_token")
            DataTool.login(self.user.text!, pass: self.password.text!,token: token, completionHandler:{ (newModel) in
                guard let newDataes = newModel else {
                    return
                }
                  print(newDataes)
                  self.modelList = newDataes
                
                if self.modelList?.msg == "登陆成功"{
                   
                SVProgressHUD.showSuccessWithStatus(self.modelList?.msg)
                   
                   NSUserDefaults.standardUserDefaults().setObject(self.user.text!, forKey: "k_UD_user")
                    NSUserDefaults.standardUserDefaults().setObject(self.password.text!, forKey: "k_UD_pass")
                    
                    NSUserDefaults.standardUserDefaults().setBool(true, forKey: "k_UD_isLogin")

                    NSUserDefaults.standardUserDefaults().synchronize()
                    
                    if self.modelList?.complete == true{
                        //分为三种个人,美容院,企业
                        NSUserDefaults.standardUserDefaults().setObject(self.modelList!.type, forKey: "k_UD_type")
                        
                    NSUserDefaults.standardUserDefaults().setBool(true, forKey: "k_UD_isComplete")
                        
                    NSUserDefaults.standardUserDefaults().synchronize()
                        
                        self.navigationController?.popToRootViewControllerAnimated(true)
                        
                    }else{
                         NSUserDefaults.standardUserDefaults().setBool(false, forKey: "k_UD_isComplete")
                        
                        let vc = self.storyboard?.instantiateViewControllerWithIdentifier("ChooseTypeTableViewController") as! ChooseTypeTableViewController
                        self.navigationController?.pushViewController(vc, animated: true)
                       
                    }

                    
                }else{
                    SVProgressHUD.showErrorWithStatus(self.modelList?.msg)
                   
                    return
                }
                
            })

        }
    }
    @IBAction func forgetPasswordBtnClicked(sender: UIButton){
        let vc = self.storyboard?.instantiateViewControllerWithIdentifier("ForgetPassWordOneVC") as! ForgetPassWordOneVC
        self.navigationController?.pushViewController(vc, animated: true)
        
    }
    
    @IBAction func QQlogin(sender: UIButton){
        self.type = "qq"
       
        ShareSDK.authorize(SSDKPlatformType.TypeQQ, settings: nil, onStateChanged: { (state : SSDKResponseState, user : SSDKUser!, error : NSError!) -> Void in
            
            switch state{
                
            case SSDKResponseState.Success: print("授权成功,用户信息为\(user)\n ----- 授权凭证为\(user.credential)")
            self.json = "\(user)"
            self.number = user.uid
            self.otherLogin()
            case SSDKResponseState.Fail:    print("授权失败,错误描述:\(error)")
            case SSDKResponseState.Cancel:  print("操作取消")
                
            default:
                break
            }
        })
        
    }
    
    @IBAction func WeiBoLogin(sender: UIButton){
        self.type = "sina"
        //授权
        ShareSDK.authorize(SSDKPlatformType.TypeSinaWeibo, settings: nil, onStateChanged: { (state : SSDKResponseState, user : SSDKUser!, error : NSError!) -> Void in
            
            switch state{
                
            case SSDKResponseState.Success: print("授权成功,用户信息为\(user)\n ----- 授权凭证为\(user.credential)")
                self.json = "\(user)"
                self.number = user.uid
                self.otherLogin()
            case SSDKResponseState.Fail:    print("授权失败,错误描述:\(error)")
            case SSDKResponseState.Cancel:  print("操作取消")
                
            default:
                break
            }
        })
    }
    
    @IBAction func weixinLogin(sener: UIButton){
        self.type = "weixin"
        ShareSDK.authorize(SSDKPlatformType.TypeWechat, settings: nil, onStateChanged: { (state : SSDKResponseState, user : SSDKUser!, error : NSError!) -> Void in
            
            switch state{
                
            case SSDKResponseState.Success: print("授权成功,用户信息为\(user)\n ----- 授权凭证为\(user.credential)")
            self.json = "\(user)"
            self.number = user.uid
            
            self.otherLogin()
            case SSDKResponseState.Fail:    print("授权失败,错误描述:\(error)")
            case SSDKResponseState.Cancel:  print("操作取消")
                
            default:
                break
            }
        })

        
    }
    
       @IBAction func registBtnClicked(sender: UIButton){
        let vc = self.storyboard?.instantiateViewControllerWithIdentifier("RegistViewController")
        self.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(vc!, animated: true)
        self.hidesBottomBarWhenPushed = false
    }
   
    //MARK: networking
    
    func otherLogin(){
        let token = NSUserDefaults.standardUserDefaults().stringForKey("k_UD_token")
        
        DataTool.QQlogin(self.json!, type: self.type!, number: self.number!,token:token!, completionHandler:{ (newModel) in
            guard newModel != nil else {
                return
            }
            self.msg = newModel
            
            NSUserDefaults.standardUserDefaults().setObject(self.msg?.phone, forKey: "k_UD_user")
            
            NSUserDefaults.standardUserDefaults().setObject(self.msg?.pass, forKey: "k_UD_pass")
            
            NSUserDefaults.standardUserDefaults().synchronize()
            
            if self.msg?.msg == "需要注册"{
                let vc = self.storyboard?.instantiateViewControllerWithIdentifier("RegistViewController") as! RegistViewController
                vc.typeID = self.number!
                vc.type = self.type!
                self.hidesBottomBarWhenPushed = true
                self.navigationController?.pushViewController(vc, animated: true)
                self.hidesBottomBarWhenPushed = false
            }
            if self.msg?.msg == "需要补全"{
                let vc = self.storyboard?.instantiateViewControllerWithIdentifier("ChooseTypeTableViewController") as! ChooseTypeTableViewController
            
                self.navigationController?.pushViewController(vc, animated: true)
            }
        
            if self.msg?.msg == "登录成功"{
                SVProgressHUD.showSuccessWithStatus(self.msg!.msg)
                
                NSUserDefaults.standardUserDefaults().setBool(true, forKey: "k_UD_isLogin")
                
                //分为三种个人,美容院,企业
                NSUserDefaults.standardUserDefaults().setObject(self.msg!.type, forKey: "k_UD_type")
                    
                NSUserDefaults.standardUserDefaults().setBool(true, forKey: "k_UD_isComplete")
                    
                NSUserDefaults.standardUserDefaults().synchronize()
                    
                self.navigationController?.popToRootViewControllerAnimated(true)
                
            }
            if self.msg?.msg == "用户已被冻结" {
                SVProgressHUD.showErrorWithStatus(self.msg?.msg)
            }
           
            
        })
    }
}
    

